﻿

using LiveCharts;
using LiveCharts.Defaults;

namespace Company.Shell.Extensions
{
    public static class ObservablePointExtension
    {
        /// <summary>
        /// 根据x得到y
        /// </summary>
        /// <param name="points"></param>
        /// <param name="x"></param>
        /// <returns></returns>
        public static ushort GetValue(this ChartValues<ObservablePoint> points,double x)
        {
            int index = 0;//下标
            foreach (var item in points)
            {
                if (item.X > x)//找到第一个大于等于 x 的点
                {
                    break;
                }
                index++;
            }
            if(index >= points.Count)//如果下标超出范围
            {
                index = points.Count - 1;//防止越界
            }

            //计算斜率
            var right = points[index];
            var left = points[index-1];//左边的点
      
            var k = (right.Y - left.Y) / (right.X - left.X);//斜率
            var b = left.Y - k * left.X;//截距
            var y = k * x + b;//计算 y 值
            return (ushort)Math.Round(y*10);//返回四舍五入的值
        }
    }
}
